package com.jdy.haoduoai.adapter;

import android.content.Intent;
import android.graphics.Bitmap;
import android.util.DisplayMetrics;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver.OnScrollChangedListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageButton;
import android.widget.LinearLayout.LayoutParams;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.jdy.haoduoai.LeXiaoXiaoBanApp;
import com.jdy.haoduoai.activity.BaseActivity;
import com.jdy.haoduoai.activity.ShareStoryDetailInfoActivity;
import com.jdy.haoduoai.activity.StoryDetailActivity;
import com.jdy.haoduoai.model.LeMachine;
import com.jdy.haoduoai.model.LePlaybackRecordWrapper;
import com.jdy.haoduoai.model.LeUser;
import com.jdy.haoduoai.util.Tools;
import com.jdy.haoduoai.view.HorizontalIndicator;
import com.jdy.haoduoai.view.NoScrollGridView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.ycsj.goldmedalnewconcept.R;

import java.util.ArrayList;

import se.emilsjolander.stickylistheaders.StickyListHeadersAdapter;

/**
 * 
 * @author hf
 * 
 */
public class RecentPlayAdapter extends BaseAdapter implements
        StickyListHeadersAdapter, SectionIndexer {

  private final ArrayList<LePlaybackRecordWrapper> mList;
  private LePlaybackRecordWrapperAdapter adapter;
  @SuppressWarnings("unused")
  private final DisplayImageOptions options;
  private DisplayMetrics dm;
  private LayoutParams params;
  private final float NUM = (float) 3.5; // 每行显示个数
  private final float LIEWIDTH;// 每列宽度
  private LeUser mLeUser;
  private LeMachine mLeMachine;

  private final BaseActivity mContext;
  private int[] mSectionIndices;
  private String[] mSectionLetters;
  private LayoutInflater mInflater;

  public RecentPlayAdapter(BaseActivity context,
      ArrayList<LePlaybackRecordWrapper> list) {
    mContext = context;

    this.mList = list;
    mInflater = LayoutInflater.from(context);
    mSectionIndices = getSectionIndices();
    mSectionLetters = getSectionLetters();

    mInflater = LayoutInflater.from(mContext);
    dm = new DisplayMetrics();
    mContext.getWindowManager().getDefaultDisplay().getMetrics(dm);
    LIEWIDTH = dm.widthPixels / NUM;

    mLeMachine = LeXiaoXiaoBanApp.getInstance().getBaby();

    if (mLeMachine == null) {
      mLeUser = LeXiaoXiaoBanApp.getInstance().getUser();
      if (mLeUser != null) {
        mLeMachine = mLeUser.machine;
      }
    }

    // 用 displayImage 加载图片 的 配置参数
    options = new DisplayImageOptions.Builder()
        .showImageOnFail(R.drawable.default_img_listitem) // 下载 失败 显示的 图片
        .cacheInMemory(true) // 缓存
        .bitmapConfig(Bitmap.Config.RGB_565) // 图片格式
        .build();
    // 创建默认的ImageLoader配置参数
    ImageLoaderConfiguration configuration = new ImageLoaderConfiguration.Builder(
        mContext).writeDebugLogs() // 打印 log 信息
        .build();
    ImageLoader.getInstance().init(configuration);
  }

  private int[] getSectionIndices() {
    int[] sections = new int[mList.size()];
    for (int i = 0; i < mList.size(); i++) {
      sections[i] = i;
    }
    return sections;
  }

  private String[] getSectionLetters() {
    String[] letters = new String[mList.size()];
    for (int i = 0; i < mList.size(); i++) {
      letters[i] = mList.get(i).dateTag;
    }
    return letters;
  }

  @Override
  public int getCount() {
    return mList.size();
  }

  @Override
  public Object getItem(int position) {
    return mList.get(position);
  }

  @Override
  public long getItemId(int position) {
    return position;
  }

  private void setListener(ViewHolder holder, LePlaybackRecordWrapper to) {
    holder.gridView.setTag(to);
  }

  private SparseArray<View> cvArray = new SparseArray<>();

  @Override
  public View getView(int position, View convertView, ViewGroup parent) {
    LePlaybackRecordWrapper menuItemVo = mList.get(position);
    ViewHolder holder;

    convertView = cvArray.get(position);

    if (convertView == null) {
      holder = new ViewHolder();
      convertView = mInflater.inflate(R.layout.recent_playbacklist_item, null);

      holder.titleText = (TextView) convertView.findViewById(R.id.titleText);
      holder.gridView = (NoScrollGridView) convertView
          .findViewById(R.id.gridview);

      holder.scrollview = (HorizontalScrollView) convertView
          .findViewById(R.id.scrollview);

      holder.mHIndicator = (HorizontalIndicator) convertView
          .findViewById(R.id.h_indicator);

      convertView.setTag(holder);
      cvArray.put(position, convertView);
      setListener(holder, menuItemVo);
    } else {
      holder = (ViewHolder) convertView.getTag();
    }

    final HorizontalIndicator hi = holder.mHIndicator;
    final HorizontalScrollView hsv = holder.scrollview;
    holder.scrollview.getViewTreeObserver().addOnScrollChangedListener(
        new OnScrollChangedListener() {
          @Override
          public void onScrollChanged() {
            int deltaX = hsv.getScrollX();
            DisplayMetrics metrics = mContext.getResources()
                .getDisplayMetrics();
            int maxX = hsv.getChildAt(0).getMeasuredWidth()
                - metrics.widthPixels + 5;
            if (hsv.getChildAt(0).getMeasuredWidth() < metrics.widthPixels) {
              hi.setVisibility(View.GONE);
              return;
            } else {
              hi.setVisibility(View.VISIBLE);
            }
            hi.onScrollChanged(deltaX, maxX);
          }
        });

    adapter = new LePlaybackRecordWrapperAdapter(mContext, menuItemVo.list,
        menuItemVo.dateTag);
    holder.titleText.setText(menuItemVo.dateTag);
    holder.gridView.setAdapter(adapter);
    params = new LayoutParams((int) (adapter.getCount() * (LIEWIDTH)),
        LayoutParams.WRAP_CONTENT);
    // holder.gridView.setHorizontalSpacing(6);
    holder.gridView.setLayoutParams(params);
    holder.gridView.setColumnWidth((int) (LIEWIDTH));
    holder.gridView.setStretchMode(GridView.NO_STRETCH);
    holder.gridView.setNumColumns(menuItemVo.list.size());

    holder.gridView.setOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view, int position,
          long id) {

        LePlaybackRecordWrapper item = (LePlaybackRecordWrapper) parent
            .getTag();

        if (Tools.isNotEmpty(item.list.get(position).catalog)) {
          if (item.list.get(position).catalog.contains("cartoon")
              || item.list.get(position).catalog.contains("radio")) {
            Intent intent = new Intent();
            intent.setClass(mContext, StoryDetailActivity.class);
            intent.putExtra("id", item.list.get(position).album_id);
            intent.putExtra("sort", item.list.get(position).episode_sort);
            mContext.startActivity(intent);
          } else {
            Intent intent = new Intent();
            intent.setClass(mContext, ShareStoryDetailInfoActivity.class);
            intent.putExtra("recentplayitem", item.list.get(position));
            mContext.startActivity(intent);
          }
        }

      }
    });

    return convertView;

  }

  @Override
  public View getHeaderView(int position, View convertView, ViewGroup parent) {
    HeaderViewHolder holder;

    if (convertView == null) {
      holder = new HeaderViewHolder();
      convertView = mInflater.inflate(R.layout.header, parent, false);
      holder.text = (TextView) convertView.findViewById(R.id.text1);
      holder.root_view = convertView.findViewById(R.id.root_view);
      convertView.setTag(holder);
    } else {
      holder = (HeaderViewHolder) convertView.getTag();
    }

    // set header text as first char in name
    // CharSequence headerChar = mCountries[position].subSequence(0, 1);

    LePlaybackRecordWrapper menuItemVo = mList.get(position);

    holder.text.setText(menuItemVo.dateTag);

    return convertView;
  }

  /**
   * Remember that these have to be static, postion=1 should always return the
   * same Id that is.
   */
  @Override
  public long getHeaderId(int position) {

    LePlaybackRecordWrapper menuItemVo = mList.get(position);
    return menuItemVo.hashCode();
  }

  @Override
  public int getPositionForSection(int section) {
    if (mSectionIndices.length == 0) {
      return 0;
    }

    if (section >= mSectionIndices.length) {
      section = mSectionIndices.length - 1;
    } else if (section < 0) {
      section = 0;
    }
    return mSectionIndices[section];
  }

  @Override
  public int getSectionForPosition(int position) {
    for (int i = 0; i < mSectionIndices.length; i++) {
      if (position < mSectionIndices[i]) {
        return i - 1;
      }
    }
    return mSectionIndices.length - 1;
  }

  @Override
  public Object[] getSections() {
    return mSectionLetters;
  }

  // public void clear() {
  // // mCountries = new String[0];
  // mSectionIndices = new int[0];
  // mSectionLetters = new String[0];
  // notifyDataSetChanged();
  // }

  // public void restore() {
  //
  // mSectionIndices = getSectionIndices();
  // mSectionLetters = getSectionLetters();
  // notifyDataSetChanged();
  // }

  class HeaderViewHolder {
    TextView text;
    View root_view;
  }

  private static class ViewHolder {
    public TextView titleText;
    private TextView view_more;
    public NoScrollGridView gridView;
    public ImageButton pushbtn;
    public HorizontalScrollView scrollview;

    public HorizontalIndicator mHIndicator;
  }

}
